package com.ruoyi.baseMain.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.alibaba.excel.annotation.ExcelProperty;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.dataMain.domain.vo.DataConsumptionVo;
import com.ruoyi.dataMain.listener.BaseAccountImportListener;
import com.ruoyi.dataMain.listener.DataConsumptionImportListener;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.baseMain.domain.vo.BaseAccountVo;
import com.ruoyi.baseMain.domain.bo.BaseAccountBo;
import com.ruoyi.baseMain.service.IBaseAccountService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 开户总表
 *
 * @author linziheng
 * @date 2023-12-31
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/baseMain/account")
public class BaseAccountController extends BaseController {

    private final IBaseAccountService iBaseAccountService;

    @GetMapping("/querySearch")
    public R<List<Map>> querySearch(String customName) {
        return iBaseAccountService.querySearch(customName);
    }
    /**
     * 查询开户总表列表
     */
    @SaCheckPermission("baseMain:account:list")
    @GetMapping("/list")
    public TableDataInfo<BaseAccountVo> list(BaseAccountBo bo, PageQuery pageQuery) {
        return iBaseAccountService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出开户总表列表
     */
    @SaCheckPermission("baseMain:account:export")
    @Log(title = "开户总表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BaseAccountBo bo, HttpServletResponse response) throws IOException {
        String filePath = "/home/file/开户总表.xlsx";  // 指定要删除的文件路径

        File file = new File(filePath);

        if (file.delete()) {
            System.out.println("文件删除成功！");
        } else {
            System.out.println("文件删除失败！");
        }

        List<BaseAccountVo> list = iBaseAccountService.queryList(bo);
        Instant start = Instant.now();
        System.out.println("当前耗时：" + Duration.between(start, Instant.now()).toMillis() + "ms");
        Workbook workbook = new SXSSFWorkbook();

        final Sheet sheet = workbook.createSheet("开户总表");
        Row row = sheet.createRow(0);

        Cell cell = row.createCell(0);
        cell.setCellValue("客户简称");

        cell = row.createCell(1);
        cell.setCellValue("合作媒体");

        cell = row.createCell(2);
        cell.setCellValue("开户日期");
        cell = row.createCell(3);
        cell.setCellValue("账户ID");
        cell = row.createCell(4);
        cell.setCellValue("账户名称");
        cell = row.createCell(5);
        cell.setCellValue("公司名称");
        cell = row.createCell(6);
        cell.setCellValue("行业类型");
        cell = row.createCell(7);
        cell.setCellValue("账户归属");
        cell = row.createCell(8);
        cell.setCellValue("业务部门");
        cell = row.createCell(9);
        cell.setCellValue("政策类别");
        cell = row.createCell(10);
        cell.setCellValue("转户日期");
        cell = row.createCell(11);
        cell.setCellValue("转入端口");
        cell = row.createCell(12);
        cell.setCellValue("销售人员");
        cell = row.createCell(13);
        cell.setCellValue("开户标签");
        cell = row.createCell(14);
        cell.setCellValue("主合同");
        cell = row.createCell(15);
        cell.setCellValue("甲方主体");


        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow(i + 1);
            cell = row.createCell(0);
            cell.setCellValue(list.get(i).getCustomName());

            cell = row.createCell(1);
            cell.setCellValue(list.get(i).getSignatory());
            cell = row.createCell(2);
            cell.setCellValue(list.get(i).getCreateDate());
            cell = row.createCell(3);
            cell.setCellValue(list.get(i).getAccountId());
            cell = row.createCell(4);
            cell.setCellValue(list.get(i).getAccountName());
            cell = row.createCell(5);
            cell.setCellValue(list.get(i).getCompanyName());
            cell = row.createCell(6);
            cell.setCellValue(list.get(i).getIndustryType());
            cell = row.createCell(7);
            cell.setCellValue(list.get(i).getAccountBelong());
            cell = row.createCell(8);
            cell.setCellValue(list.get(i).getBusinessUnitName());
            cell = row.createCell(9);
            cell.setCellValue(list.get(i).getBidding());
            cell = row.createCell(10);
            cell.setCellValue(list.get(i).getTrunDate());
            cell = row.createCell(11);
            cell.setCellValue(list.get(i).getSupplierId());
            cell = row.createCell(12);
            cell.setCellValue(list.get(i).getSaleUserName());
            cell = row.createCell(13);
            cell.setCellValue(list.get(i).getAccountTag());
            cell = row.createCell(14);
            cell.setCellValue(list.get(i).getMainParty());
            cell = row.createCell(15);
            cell.setCellValue(list.get(i).getAparty());
        }
        System.out.println("当前耗时：" + Duration.between(start, Instant.now()).toMillis() + "ms");
        workbook.write(Files.newOutputStream(Paths.get("/home/file/", "开户总表.xlsx")));
        System.out.println("当前耗时：" + Duration.between(start, Instant.now()).toMillis() + "ms");
//        ExcelUtil.exportExcel(list, "开户总表", BaseAccountVo.class, response);
    }
    /**
     * 导入数据
     *
     * @param file          导入文件
     */
    @Log(title = "开户导入", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file) throws Exception {
        ExcelResult<BaseAccountVo> result = ExcelUtil.importExcel(file.getInputStream(), BaseAccountVo.class, new BaseAccountImportListener());
        return R.ok(result.getAnalysis());
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "消耗总表", DataConsumptionVo.class, response);
    }
    /**
     * 获取开户总表详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("baseMain:account:query")
    @GetMapping("/{id}")
    public R<BaseAccountVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        BaseAccountVo vo =  iBaseAccountService.queryById(id);
        vo.setBiddingId(vo.getBidding());
        return R.ok(vo);
    }

    /**
     * 新增开户总表
     */
    @SaCheckPermission("baseMain:account:add")
    @Log(title = "开户总表", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BaseAccountBo bo) {
        return toAjax(iBaseAccountService.insertByBo(bo));
    }

    /**
     * 修改开户总表
     */
    @SaCheckPermission("baseMain:account:edit")
    @Log(title = "开户总表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BaseAccountBo bo) {
        return toAjax(iBaseAccountService.updateByBo(bo));
    }

    /**
     * 批量修改开户总表
     */
    @SaCheckPermission("baseMain:account:edit")
    @Log(title = "开户总表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/batchEdit")
    public R<Void> batchEdit(@Validated(EditGroup.class) @RequestBody BaseAccountBo bo) {
        return toAjax(iBaseAccountService.batchEdit(bo));
    }

    /**
     * 删除开户总表
     *
     * @param ids 主键串
     */
    @SaCheckPermission("baseMain:account:remove")
    @Log(title = "开户总表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iBaseAccountService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
